package practise.mulitThreads.ConcurrentInPractice.CustomerizedSemaphore;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by richard on 6/14/14.
 */
public class CustomerizedSemphore {
    Lock lock = new ReentrantLock();
    Condition permit = lock.newCondition();
    AtomicInteger signal;
    public CustomerizedSemphore(int signal){
        this.signal = new AtomicInteger(signal);
    }

    public void acquire(){
        try {
        for(;;)
        if(signal.decrementAndGet()>0)
            break;
        else{
            waitWhenNoPermit();
            signal.incrementAndGet();//compensate the value if not get the lock
        }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    }

    public void release(){
        signal.incrementAndGet();
        notifyForPermit();
    }

    private void waitWhenNoPermit() throws InterruptedException {
        lock.lock();
        try{
            permit.await();
        }
        finally {
           lock.unlock();
        }
    }

    private void notifyForPermit(){
        lock.lock();
        try {
            permit.signal();
        }
        finally {
            lock.unlock();
        }
    }

}
